//
//  JDExtractViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/12/31.
//

import UIKit
import SwiftyJSON
import ProgressHUD

class JDExtractViewController: JDBaseViewController {
    
    var bottomContainerView: UIView?
    var extractButton: UIButton?
    
    var walletLabel: UILabel?
    var extractInputView: UITextField?
    var extractTypeTableView: UITableView?
    var canExtractLabel: UILabel?
    
    var selectedIndex: Int = -1
    
    var extractInfoModel: JDExtractInfoModel?
    
    var balanceModel: JDBalanceModel?
    
    var cashOutCompleted:(()->())?
    
    /// 绑定信息
    var bindModel: JDPaymentBindmodel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(bindWechatResult(_:)), name: NSNotification.Name.init("bindWechatResult"), object: nil)
        
        // Do any additional setup after loading the view.
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.fetchUserBalance()
    }
    /// 获取用户账户余额，可提现金额
    func fetchUserBalance() {
        JDNetWorkRequest(.fetchUserBalance([:])) { responseStr in
            
            print("这里的返回:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
//                JDBalanceModel
                
                if let balanceModel = JDBalanceModel.deserialize(from: responseStr, designatedPath: "data") {
                    
                    self.balanceModel = balanceModel
                    
                    self.canExtractLabel?.text =  String(format: "可提现余额:￥%@", self.balanceModel?.balanceText ?? "0.00")
//                    self.canExtractLabel?.priceString(UIFont.systemFont(ofSize: 16, weight: .semibold), UIFont.systemFont(ofSize: 32, weight: .semibold))
                    
                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    
    @objc func bindWechatResult(_ notify: NSNotification) {
        
        let userInfo = notify.userInfo
        
        let wechatKey = userInfo?["wechatKey"] as? Any
        
        // TODO: 这里获取到code以后，应该是调用后台接口，获取到当前用户的昵称和头像等信息，然后再进行bindAliPayAccount这个方法
        
        
        var params = [String: Any]()
        params["code"] = JSON(wechatKey as Any).stringValue
        JDNetWorkRequest(.getWechatUserInfo(params)) { responseStr in
            
            print("返回值AAA:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                print("返回值BBB:\(commonModel?.data)")
                
                if let wechatInfoModel = JDWechatResponseModel.deserialize(from: responseStr, designatedPath: "data") {
                 
                    
                    var wxpayInfoDic = [String: Any]()
                    wxpayInfoDic["wechatCode"] = wechatInfoModel.openId
                    wxpayInfoDic["nickname"] = wechatInfoModel.nickname
                    wxpayInfoDic["headImgUrl"] = wechatInfoModel.headImgUrl
                    
                    self.bindAliPayAccount(type: "wxpay", resultDic: wxpayInfoDic, true)
                    
//                    self.bindAliPayAccount(type: "wxpay", resultDic: ["wechatCode": wechatKey as Any], true)
                }
                
//                返回值AAA:{"code":"0","success":true,"data":{"headImgUrl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/DYAIOgq83eqSgQPkJPBCv0EsQZ4DWNkMjKX7acKKjaB5Yry1wtHZ9qrduSicv7Ksojl1Cb2K4ibZ3qAfhqRabFtg\/132","nickname":"volantPig","openId":"o_nLQ67cyXAit7_mzUa-3D8CxOrU"},"msg":"OK"}
//                返回值BBB:Optional({
//                    headImgUrl = "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqSgQPkJPBCv0EsQZ4DWNkMjKX7acKKjaB5Yry1wtHZ9qrduSicv7Ksojl1Cb2K4ibZ3qAfhqRabFtg/132";
//                    nickname = volantPig;
//                    openId = "o_nLQ67cyXAit7_mzUa-3D8CxOrU";
//                })
                
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

        
    }
    
    func setupConfig() {
        self.setupNavigationTitle("提现")
        self.setupLeftBackItem()
    }
    
    func setupUIElements() {
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(bottomSaftAreaHeight+50+14)
        })
        self.bottomContainerView?.backgroundColor = .white
        
        self.extractButton = UIButton(type: .system)
        self.bottomContainerView?.addSubview(self.extractButton!)
        self.extractButton?.snp.makeConstraints({ make in
            make.leading.equalTo(self.bottomContainerView!).offset(12)
            make.trailing.equalTo(self.bottomContainerView!).offset(-12)
            make.top.equalTo(self.bottomContainerView!).offset(14)
            make.height.equalTo(50)
        })
        self.extractButton?.makeCorner(25)
        self.extractButton?.buttonConfig(normalTitle: "去提现", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 16, weight: .regular), backgroundColor: color("#FA6161"))
        self.extractButton?.addTarget(self, action: #selector(extractAction), for: .touchUpInside)
        
        let topContainerView = UIView()
        self.view.addSubview(topContainerView)
        topContainerView.snp.makeConstraints({ make in
            make.leading.equalTo(self.view).offset(12)
            make.trailing.equalTo(self.view).offset(-12)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            
        })
        topContainerView.makeCorner(8)
        topContainerView.backgroundColor = .white
        
        let topTitle = UILabel()
        topContainerView.addSubview(topTitle)
        topTitle.snp.makeConstraints { make in
            make.leading.equalTo(topContainerView).offset(12)
            make.top.equalTo(topContainerView).offset(20)
            make.height.equalTo(20)
        }
        topTitle.text = "提现金额"
        topTitle.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        self.walletLabel = UILabel()
        topContainerView.addSubview(self.walletLabel!)
        self.walletLabel?.snp.makeConstraints({ make in
            make.leading.equalTo(topTitle)
            make.top.equalTo(topTitle.snp.bottom).offset(6)
            make.height.equalTo(45)
        })
        self.walletLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"), numberOfLines: 1)
        self.walletLabel?.text = "￥"
//        self.walletLabel?.priceString(UIFont.systemFont(ofSize: 16, weight: .semibold), UIFont.systemFont(ofSize: 32, weight: .semibold))
        self.walletLabel?.setContentHuggingPriority(.required, for: .horizontal)
        
        self.extractInputView = UITextField()
        topContainerView.addSubview(self.extractInputView!)
        self.extractInputView?.snp.makeConstraints({ make in
            make.leading.equalTo(self.walletLabel!.snp.trailing)
            make.top.bottom.equalTo(self.walletLabel!)
            make.trailing.equalTo(topContainerView).offset(-6)
        })
        self.extractInputView?.placeholder = "请输入提现金额"
        self.extractInputView?.delegate = self
        self.extractInputView?.keyboardType = .decimalPad
        
        let topLine = UIView()
        topContainerView.addSubview(topLine)
        topLine.snp.makeConstraints { make in
            make.top.equalTo(self.walletLabel!.snp.bottom).offset(3)
            make.leading.equalTo(topContainerView).offset(12)
            make.trailing.equalTo(topContainerView).offset(-12)
            make.height.equalTo(1)
            make.bottom.equalTo(topContainerView).offset(-43)
        }
        topLine.backgroundColor = .commonColor()
        
        self.canExtractLabel = UILabel()
        topContainerView.addSubview(self.canExtractLabel!)
        self.canExtractLabel?.snp.makeConstraints({ make in
            make.leading.equalTo(topContainerView).offset(12)
            make.top.equalTo(topLine.snp.bottom)
            make.bottom.equalTo(topContainerView)
        })
        self.canExtractLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        self.canExtractLabel?.text =  String(format: "可提现余额:￥%@", self.balanceModel?.balanceText ?? "0.00")
        
        let extracDescriptionLabel = UILabel()
        topContainerView.addSubview(extracDescriptionLabel)
        extracDescriptionLabel.snp.makeConstraints { make in
            make.trailing.equalTo(topContainerView).offset(-12)
            make.centerY.equalTo(self.canExtractLabel!)
        }
        extracDescriptionLabel.text = " 平台单笔提现金额>=￥25"
        extracDescriptionLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#9DA1B2"), numberOfLines: 1)
        extracDescriptionLabel.appendImgV("hint_alert", at: 0)
        
//        let descriptionButton = UIButton(type: .custom)
//        topContainerView.addSubview(descriptionButton)
//        descriptionButton.snp.makeConstraints { make in
//            make.centerY.equalTo(extracDescriptionLabel)
//            make.trailing.equalTo(extracDescriptionLabel.snp.leading).offset(-6)
//            make.size.equalTo(CGSizeMake(14, 14))
//        }
//        descriptionButton.setImage(UIImage(named: "hint_alert"), for: .normal)
        
        // MARK: tableView
        self.extractTypeTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.extractTypeTableView!)
        self.extractTypeTableView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.top.equalTo(topContainerView.snp.bottom)
            make.bottom.equalTo(self.bottomContainerView!.snp.top).offset(-10)
        })
        self.extractTypeTableView?.delegate = self
        self.extractTypeTableView?.dataSource = self
        self.extractTypeTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
        self.extractTypeTableView?.backgroundColor = .commonColor()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func getNetData() {
        JDNetWorkRequest(.getCashOutPageInfo) { responseStr in
//            {"code":"0","success":true,"message":"OK","data":{"userId":31,"certNo":null,"alipayAccount":"2088502457221332","id":2,"realName":null,"updatedAt":"2025-04-05T20:15:51","deleteFlag":0,"createdAt":"2025-04-05T20:15:51","wxpayAccount":null}}
            
            print("提现返回信息:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let model = JDExtractInfoModel.deserialize(from: responseStr, designatedPath: "data") {
                    self.extractInfoModel = model
                    self.extractTypeTableView?.reloadData()
                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
}

extension JDExtractViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
        for subV in cell?.contentView.subviews ?? [UIView]() {
            subV.removeFromSuperview()
        }
        cell?.contentView.backgroundColor = .commonColor()

        let containerView = UIView()
        cell?.contentView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.leading.equalTo(cell!.contentView).offset(12)
            make.trailing.equalTo(cell!.contentView).offset(-12)
            make.top.equalTo(cell!.contentView).offset(10)
            make.height.equalTo(79)
            make.bottom.equalTo(cell!.contentView)
        }
        containerView.makeCorner(8)
        containerView.backgroundColor = .white
        
        let iconImageV = UIImageView()
        containerView.addSubview(iconImageV)
        iconImageV.snp.makeConstraints { make in
            make.leading.equalTo(containerView).offset(12)
            make.centerY.equalTo(containerView)
            make.size.equalTo(CGSizeMake(32, 32))
        }
        
        let titleStr = UILabel()
        containerView.addSubview(titleStr)
        titleStr.snp.makeConstraints { make in
            make.leading.equalTo(iconImageV.snp.trailing).offset(16)
            make.top.equalTo(iconImageV.snp.top).offset(-7)
            make.height.equalTo(22)
        }
        titleStr.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        let descriptionLabel = LinkLabel()
        containerView.addSubview(descriptionLabel)
        descriptionLabel.snp.makeConstraints { make in
            make.leading.equalTo(titleStr)
            make.top.equalTo(titleStr.snp.bottom).offset(4)
            make.height.equalTo(20)
        }
        descriptionLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#9DA1B2"), numberOfLines: 1)
        
        let bindButton = UIButton(type: .custom)
        containerView.addSubview(bindButton)
        bindButton.snp.makeConstraints { make in
            make.trailing.equalTo(containerView).offset(-12)
            make.centerY.equalTo(containerView)
            make.size.equalTo(CGSizeMake(62, 32))
        }
        bindButton.buttonConfig(normalTitle: "去绑定", normalTitleColor: color("#FA6161"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: .white)
        bindButton.makeCorner(4)
        bindButton.makeBorder(color("#FA6161"), 1)
        bindButton.addTarget(self, action: #selector(bindAction(_:)), for: .touchUpInside)
        bindButton.tag = indexPath.row
        
        let selectedButton = UIButton(type: .custom)
        containerView.addSubview(selectedButton)
        selectedButton.snp.makeConstraints { make in
            make.trailing.equalTo(containerView).offset(-12)
            make.centerY.equalTo(containerView)
            make.size.equalTo(CGSizeMake(22, 22))
        }
        selectedButton.tag = indexPath.row
        selectedButton.setImage(UIImage(named: "circle_unSelected"), for: .normal)
        selectedButton.setImage(UIImage(named: "circle_selected"), for: .selected)
        selectedButton.addTarget(self, action: #selector(selectedButtonAction(_:)), for: .touchUpInside)
                
        if indexPath.row == 0 {
            iconImageV.image = UIImage(named: "mine_alipay")
            titleStr.text = "提现至支付宝"

            if (self.extractInfoModel?.alipayAccount?.count ?? 0) > 0 {
                // 已经进行了实名认证
                bindButton.isHidden = true
                selectedButton.isHidden = false
                
                let linkModel = LinkLabelModel()
                linkModel.linkString = "解绑 >"
                linkModel.linkStrAttributes = [NSAttributedString.Key.foregroundColor: color("#333333"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any]
                
                descriptionLabel.configureLinkInfo("支付宝昵称 : \(self.extractInfoModel?.alipayNickname ?? "") | 解绑 >", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any ], [linkModel])
                
                descriptionLabel.selectLinkStringCompeleted = { [weak self] linkStr in
                    if linkStr == "解绑 >" {
                        printLog("解绑操作吧")
                        
                        let popupConfirmView = JDPopupConfirmView()
                        popupConfirmView.confirmButtonSelected = {
                            self?.bindAliPayAccount(type: "alipay", resultDic: [:], false)
                        }
                        popupConfirmView.titleStr = "您确定解绑此支付宝吗？"
                        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
                    }
                }
                
                if indexPath.row == self.selectedIndex {
                    selectedButton.isSelected = true
                } else {
                    selectedButton.isSelected = false
                }
                
            } else {
                // 尚未完成实名认证
                selectedButton.isHidden = true
                descriptionLabel.isHidden = false
                descriptionLabel.configureLinkInfo("请绑定已经实名的支付宝账号", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any ], [])
            }
        } else if indexPath.row == 1 {
            iconImageV.image = UIImage(named: "mine_wechat")
            titleStr.text = "提现至微信"

            if (self.extractInfoModel?.wechatpayNickname?.count ?? 0) > 0 {
                // TODO: 富文本超链接
                bindButton.isHidden = true
                
                let linkModel = LinkLabelModel()
                linkModel.linkString = "解绑 >"
                linkModel.linkStrAttributes = [NSAttributedString.Key.foregroundColor: color("#333333"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any]
                
//                descriptionLabel.configureLinkInfo("微信昵称 : 微信昵称 | 解绑 >", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any ], [linkModel])
                descriptionLabel.configureLinkInfo("微信昵称 : \(self.extractInfoModel?.wechatpayNickname ?? "") | 解绑 >", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any ], [linkModel])
                
                descriptionLabel.selectLinkStringCompeleted = { [weak self] linkStr in
                    if linkStr == "解绑 >" {
                        let popupConfirmView = JDPopupConfirmView()
                        popupConfirmView.confirmButtonSelected = {
                            self?.bindAliPayAccount(type: "wxpay", resultDic: [:], false)
                        }
                        popupConfirmView.titleStr = "您确定解绑此微信用户吗？"
                        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
                    }
                }
                
                if indexPath.row == self.selectedIndex {
                    selectedButton.isSelected = true
                } else {
                    selectedButton.isSelected = false
                }
            } else {
                selectedButton.isHidden = true
                descriptionLabel.isHidden = false
                descriptionLabel.configureLinkInfo("请绑定已经实名的微信账号", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 14, weight: .regular) as Any ], [])
            }
        }
        
        return cell!
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    
}

extension JDExtractViewController {
    
    @objc func bindAction(_ button: UIButton) {
        
        if (self.extractInfoModel?.realName?.count ?? 0) <= 0 || (self.extractInfoModel?.certNo?.count ?? 0) <= 0 {
            
            let newAuthenticationView = JDNewAuthenticationView()
            newAuthenticationView.titleLabel?.text = "提现实名认证信息"
            newAuthenticationView.hintLabel?.text = "确认授权微信与支付宝使用身份证信息进行提现审核。"
            newAuthenticationView.isUpdate = true
            newAuthenticationView.confirmButtonSelected = { [weak self] realName, idCardNo in
                // 认证完成之后的操作
                self?.extractInfoModel?.realName = realName
                self?.extractInfoModel?.certNo = idCardNo
                
                self?.view.toast(message: "认证成功")
            }
            JDTools.getKeyWindows()?.rootViewController?.view.addSubview(newAuthenticationView)
            
            return
        }
        
        
        let buttonTag = button.tag
        if buttonTag == 0 {
            print("支付宝")
            JDAlipayManager.alipayAuthorizationAction {[weak self] responseDic in
                print("调用绑定接口:\(responseDic)")
    //            ["auth_code": "c459b38e798945cab878a1f80906QB33", "app_id": "2021005107601969", "result_code": "200", "target_id": "1743841585871772734367", "user_id": "2088502457221332", "alipay_open_id": "20880018885218778922708660117333", "scope": "auth_base", "success": "true"]
                
                
                
                let code = JSON(responseDic["auth_code"] as Any).stringValue
                
                var params = [String: Any]()
                params["code"] = code
                JDNetWorkRequest(.getAlipayUserInfo(params)) { responseStr in
                    
                    let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                    if commonModel?.code == "0" {
                        print("接口返回内容:\(commonModel?.data)")
//                        接口返回内容:Optional({
//                            avatar = "<null>";
//                            nickname = volantPig;
//                            userId = "033dTYioh1hxJbW6TuGF93VE7-GhX1ZkAvbMgxTcgFnVdIf";
//                        })
                        var alipayInfoDic = responseDic
                        alipayInfoDic["avatar"] = JSON(commonModel?.data as Any).dictionaryValue["avatar"]?.stringValue
                        alipayInfoDic["nickname"] = JSON(commonModel?.data as Any).dictionaryValue["nickname"]?.stringValue
                        alipayInfoDic["userId"] = JSON(commonModel?.data as Any).dictionaryValue["userId"]?.stringValue
                        self?.bindAliPayAccount(type: "alipay", resultDic: alipayInfoDic)
                    }
                } failure: { error in
                    
                } error: { errorCode in
                        
                }

            }
        } else {
            print("微信")
            // TODO: 微信的回调，可能是在AppDelegate里回到，这里可以注册一个通知，然后，再走后续操作
            JDWechatManager.sendAuthRequest()
        }
        
    }
    
    /// 绑定支付宝   type入参值: wxpay / alipay
    func bindAliPayAccount(type: String, resultDic:[String: Any],_ isBind: Bool = true ) {
        
//        ["auth_code": "c459b38e798945cab878a1f80906QB33", "app_id": "2021005107601969", "result_code": "200", "target_id": "1743841585871772734367", "user_id": "2088502457221332", "alipay_open_id": "20880018885218778922708660117333", "scope": "auth_base", "success": "true"]
        
        var params = [String: Any]()
//        wxpay / alipay
        params["type"] = type
        if type == "alipay" {
            // 支付宝
            if isBind {
                params["payAccount"] = JSON(resultDic["userId"] as Any).stringValue
                params["authCode"] = JSON(resultDic["auth_code"] as Any).stringValue
                params["alipayHeaderImg"] = JSON(resultDic["avatar"] as Any).stringValue
                params["alipayNickname"] = JSON(resultDic["nickname"] as Any).stringValue
            } else {
                params["payAccount"] = ""
                params["authCode"] = ""
                params["alipayHeaderImg"] = ""
                params["alipayNickname"] = ""
            }
            
        } else {
            // 微信 未知
            if isBind {
                params["payAccount"] = ""
                params["authCode"] = JSON(resultDic["wechatCode"] as Any).stringValue
                params["wechatpayHeaderImg"] = JSON(resultDic["headImgUrl"] as Any).stringValue
                params["wechatpayNickname"] = JSON(resultDic["nickname"] as Any).stringValue
            } else {
                params["payAccount"] = ""
                params["authCode"] = ""
                params["wechatpayHeaderImg"] = ""
                params["wechatpayNickname"] = ""
            }
        }
        
        JDNetWorkRequest(.bindPayAccountByUserId(params)) { responseStr in
            
            print("绑定结果:\(responseStr)")
//            绑定结果:{"code":"0","success":true,"message":"OK","data":true}
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let model = JDPaymentBindmodel.deserialize(from: responseStr, designatedPath: "data") {
                    self.bindModel = model
                    
                    if type == "alipay" {
                        self.extractInfoModel?.alipayNickname = self.bindModel?.alipayNickname
                        self.extractInfoModel?.alipayHeaderImg = self.bindModel?.alipayHeaderImg
                    } else {
                        self.extractInfoModel?.wechatpayNickname = self.bindModel?.wechatpayNickname
                        self.extractInfoModel?.wechatpayHeaderImg = self.bindModel?.wechatpayHeaderImg
                    }
                }
//                {"wechatpayNickname":null,"alipayHeaderImg":"https:\/\/devresource.xiaolongbaobao.com\/headerImg\/alipay.png","alipayNickname":"volantPig","wechatpayHeaderImg":null}
                
                self.view.toast(message: "绑定成功")
                self.getNetData()
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    
    
    @objc func selectedButtonAction(_ button: UIButton) {
        
        if self.selectedIndex == button.tag {
            self.selectedIndex = -1
        } else {
            self.selectedIndex = button.tag
        }
        button.isSelected = !button.isSelected
        self.extractTypeTableView?.reloadData()
    }
    
    @objc func extractAction() {
        
        if self.selectedIndex == -1 {
            self.view.toast(message: "请选择提现方式")
            return
        }
        
        let cashOutNumber = JSON(self.extractInputView?.text as Any).doubleValue
        
        if cashOutNumber <= 0 {
            self.view.toast(message: "请输入提现金额")
            return
        }
        
        if JSON(self.balanceModel?.balanceText as Any).doubleValue < cashOutNumber {
            self.view.toast(message: "提现金额超过最大可提现数额")
            return
        }
        
//        if (self.extractInputView?.text?.count ?? 0) <= 25 {
//            self.view.toast(message: "提现金额不满足最低要求")
//            return
//        }
        
        if (self.extractInfoModel?.realName?.count ?? 0) <= 0 || (self.extractInfoModel?.certNo?.count ?? 0) <= 0 {
          // 未进行实名认证 直接拦截吧 暂时不做提示  后期 考虑一下 进行一个什么提示比较好
            return
        }
        let extractAgainView = JDExtractConfirmAgainView()
        if self.selectedIndex == 0 {
            extractAgainView.nameTitle?.text = "支付宝昵称"
            extractAgainView.nameLabel?.text = self.extractInfoModel?.alipayNickname
            extractAgainView.extractNumberLabel?.text = String(format: "¥%@", self.extractInputView?.text ?? "0.00")
            extractAgainView.extractNumberLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .semibold), UIFont.systemFont(ofSize: 18, weight: .semibold))
            extractAgainView.userPortraitImageV?.kf.setImage(with: URL(string: self.extractInfoModel?.alipayHeaderImg ?? ""), placeholder: UIImage(named: "aliapy_portrait"), options: nil, completionHandler: nil)
        } else if self.selectedIndex == 1 {
            extractAgainView.nameTitle?.text = "微信昵称"
            extractAgainView.nameLabel?.text = self.extractInfoModel?.wechatpayNickname
            extractAgainView.extractNumberLabel?.text = String(format: "¥%@", self.extractInputView?.text ?? "0.00")
            extractAgainView.extractNumberLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .semibold), UIFont.systemFont(ofSize: 18, weight: .semibold))
            extractAgainView.userPortraitImageV?.kf.setImage(with: URL(string: self.extractInfoModel?.wechatpayHeaderImg ?? ""), placeholder: UIImage(named: "aliapy_portrait"), options: nil, completionHandler: nil)
        }
        
        extractAgainView.confirmButtonSelected = { [weak self] in
            print("确定提现了")
            if self?.selectedIndex == 0 {
                ProgressHUD.animate()
                print("支付宝提现")
                self?.cashOutRequst("alipay")
            } else if self?.selectedIndex == 1 {
                ProgressHUD.animate()
                print("微信提现吧")
                /// 提现请求     wxpay / alipay
                self?.cashOutRequst("wxpay")
            }
        }

        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(extractAgainView)
    }
    
    /// 提现请求     wxpay / alipay
    func cashOutRequst(_ type:String) {
        
        let cashOutNumber = JSON(self.extractInputView?.text as Any).doubleValue
        if cashOutNumber <= 0 {
            self.view.toast(message: "提现异常")
            return
        }
        
        var params = [String: Any]()
        params["amount"] = self.extractInputView?.text
        params["type"] = type
        JDNetWorkRequest(.userCashOut(params)) { responseStr in
            ProgressHUD.dismiss()
            print("提现操作:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                self.view.toast(message: "提现成功")
                
                
                let cashOutVC = JDCashoutSuccessViewController()
                cashOutVC.cashoutType = type
                cashOutVC.cashoutNumber = self.extractInputView?.text ?? ""
                if type == "wxpay" {
                    cashOutVC.cashoutNicknameString = self.extractInfoModel?.wechatpayNickname ?? ""
                } else if type == "alipay" {
                    cashOutVC.cashoutNicknameString = self.extractInfoModel?.alipayNickname ?? ""
                }
                self.hidesBottomBarPushViewController(cashOutVC)
                

                // 之后 应该再刷新一下【我的现金账目】页面
                self.cashOutCompleted?()
            } else {
                self.view.toast(message: commonModel?.message ?? "服务器异常")
            }
        } failure: { error in
            ProgressHUD.dismiss()
            self.view.toast(message: "服务器异常")
            
        } error: { errorCode in
            ProgressHUD.dismiss()
            print("提现异常:\(errorCode)")
            self.view.toast(message: "错误代码:\(errorCode)")
            
        }

    }
    
}

extension JDExtractViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if textField == self.extractInputView {
            
            // 首位输入"."
            if (textField.text?.count ?? 0) == 0 && string == "." {
                textField.text = "0" + string
                return false
            }

            
            if (textField.text?.count ?? 0) >= 13 && string != "" {
                return false
            }
            
//            if !string.isNumberInputRange() {
//                return false
//            }

            if string == "-" {
                if textField.text?.contains(string) ?? false {
                    if let currentStr = textField.text {
                        let startIndex = currentStr.index(currentStr.startIndex, offsetBy: 1)
                        let subString = currentStr.suffix(from: startIndex)
                        textField.text = String(subString)
                    }
                } else {
                    textField.text = string + (textField.text ?? "")
                }
                return false
            }
            
            if textField.text == "0" {
                if string == "0" {
                    return false
                } else {
                    if string == "." {
                        return true
                    }
                    textField.text = string
                    return false
                }
            }
            
            if textField.text?.contains(".") ?? false {
                if string == "." {
                    return false
                }
                let numberArray = textField.text?.components(separatedBy: ".")
                
                if (numberArray?.last?.count ?? 0) >= 6 {
                    
                    if string == "" {
                        return true
                    }
                    return false
                }
            } else {
                if (textField.text?.count ?? 0) >= 13 {
                    if string == "" {
                        return true
                    }
                    return false
                }
            }
        }
        if !(textField.text?.contains(".") ?? true) && string == ".", (textField.text?.count ?? 0) > 0 {

            var temporaryStr = textField.text ?? ""
            let index = temporaryStr.index(temporaryStr.startIndex, offsetBy: range.location)
            temporaryStr.insert(".", at: index)

            let numberArray = temporaryStr.components(separatedBy: ".")
            let intStr = (numberArray.first ?? "").count > 0 ? (numberArray.first ?? "") : "0"
            let dotStr = numberArray.last ?? ""
            var newDotStr = dotStr
           
            textField.text = String(format: "%@%@%@", intStr,string,newDotStr)
            return false
        }
        return true
    }
}
